package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.ImportDataExcelStatus;
import cn.fintecher.pangolin.common.enums.MessageType;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.DataImportRecord;
import cn.fintecher.pangolin.entity.elastic.LeaveCaseModel;
import cn.fintecher.pangolin.service.dataimp.elastic.BaseCaseElastic;
import cn.fintecher.pangolin.service.dataimp.elastic.DataImportRecordElastic;
import cn.fintecher.pangolin.service.dataimp.model.ConfirmModel;
import cn.fintecher.pangolin.service.dataimp.repository.CaseInfoRepository;
import cn.fintecher.pangolin.service.dataimp.service.BaseService;
import cn.fintecher.pangolin.common.utils.RepositoryUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:55 2019/10/15
 */

@Service("ConfirmLeaveTask")
public class ConfirmLeaveTask {
    private static final Logger log = LoggerFactory.getLogger(ConfirmLeaveTask.class);

    @Autowired
    private DataImportRecordElastic dataImportRecordElastic;

    @Autowired
    private CaseInfoRepository caseInfoRepository;

    @Autowired
    private BaseCaseElastic baseCaseElastic;

    @Autowired
    private BaseService baseService;

    @Autowired
    private ConfirmLeaveFuture confirmLeaveFuture;

    /**
     * 留案导入确认
     */
    @Async
    @Transactional
    public void confirmLeave(List<LeaveCaseModel> models, UserModel userModel, DataImportRecord record) {
        //创建任务集合
        List<CompletableFuture<ConfirmModel>> list = new ArrayList<>();
        //分页处理信息
        int pageSize = 2000;
        int pageNumber = (int) Math.ceil((double) models.size() / (double) pageSize);
        for (int i = 0; i < pageNumber; i++) {
            List<LeaveCaseModel> leaveCaseModels = models.stream().skip(i * pageSize).limit(pageSize).collect(Collectors.toList());
            CompletableFuture<ConfirmModel> task = confirmLeaveFuture.processLeave(leaveCaseModels);
            list.add(task);
        }
        List<ConfirmModel> confirmModels = new ArrayList<>();
        try {
            for (CompletableFuture<ConfirmModel> future : list) {
                ConfirmModel model = future.get();
                confirmModels.add(model);
            }
            if (!confirmModels.isEmpty()) {
                confirmModels.forEach(e -> {
                    RepositoryUtil.saveData(caseInfoRepository, e.getCaseInfos());
                    RepositoryUtil.saveData(baseCaseElastic, e.getBaseCases());
                });
            }
            //更新导入结果状态
            record.setStatus(ImportDataExcelStatus.CONFIRMED);
            record.process(userModel.getRealName(), ZWDateUtil.getNowDateTime());
            dataImportRecordElastic.save(record);
        } catch (InterruptedException | ExecutionException e) {
            log.error(e.getMessage(), e);
            record.setStatus(ImportDataExcelStatus.UN_CONFIRMED);
            record.process(userModel.getRealName(), ZWDateUtil.getNowDateTime());
            dataImportRecordElastic.save(record);
        } finally {
            baseService.sendMsg(MessageType.IMPORT_LEFT_CONFIRMED, userModel);
        }
    }
}
